import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
// 全局注册路由
Vue.use(VueRouter)
// 配置路由路径
const router = new VueRouter({
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login')
    },
    {
      path: '/',
      component: () => import('@/views/layout'),
      redirect: '/home',
      // 下面是二级路由
      children: [
        {
          path: '/home',
          component: () => import('@/views/layout/home')
        },
        {
          path: '/question',
          component: () => import('@/views/layout/question')
        },
        {
          path: '/video',
          component: () => import('@/views/layout/video')
        },
        {
          path: '/user',
          component: () => import('@/views/layout/user')
        }
      ]
    },
    {
      path: '/search',
      component: () => import('@/views/search')
    },
    {
      path: '/article',
      component: () => import('@/views/article')
    },
    {
      path: '/searchResult',
      component: () => import('@/views/search/result')
    },
    {
      path: '/404',
      component: () => import('@/views/404')
    }
  ]
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
// 需要认证的页面
const AuthUrls = ['/user']
router.beforeEach((to, from, next) => {
  const token = store.state.user.tokenInfo.token
  // 如果是去 /login, 判断 token 存不存在, 如果 token 存在说明登录过了, 直接跳转到首页
  if (to.path === '/login' && token) {
    next('/')
    return
  }
  // 如果是需要授权的页面
  if (AuthUrls.includes(to.path)) {
    // 进行验证身份
    // console.log(token)
    if (token) {
      next()
    } else {
      // console.log(to)
      // 拦截到登录
      next({
        path: '/login',
        query: {
          backto: to.fullPath
        }
      })
    }
  } else {
    next()
  }
})
export default router
